package com.buli.blmall.generator.convert;


import com.buli.blmall.generator.enums.DbColumnType;
import com.buli.blmall.generator.metadata.MetaTable;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xiang.gao
 * @date 2024/12/9 15:47
 */
public class JdbcTypeConvert {
    private static final Map<Integer, DbColumnType> typeMap = new HashMap();

    static {
        typeMap.put(-2, DbColumnType.BYTE_ARRAY);
        typeMap.put(2004, DbColumnType.BYTE_ARRAY);
        typeMap.put(-4, DbColumnType.BYTE_ARRAY);
        typeMap.put(-3, DbColumnType.BYTE_ARRAY);
        typeMap.put(-6, DbColumnType.BYTE);
        typeMap.put(-5, DbColumnType.LONG);
        typeMap.put(-7, DbColumnType.BOOLEAN);
        typeMap.put(16, DbColumnType.BOOLEAN);
        typeMap.put(5, DbColumnType.SHORT);
        typeMap.put(1, DbColumnType.STRING);
        typeMap.put(2005, DbColumnType.STRING);
        typeMap.put(12, DbColumnType.STRING);
        typeMap.put(-1, DbColumnType.STRING);
        typeMap.put(-16, DbColumnType.STRING);
        typeMap.put(-15, DbColumnType.STRING);
        typeMap.put(2011, DbColumnType.STRING);
        typeMap.put(-9, DbColumnType.STRING);
        typeMap.put(91, DbColumnType.DATE);
        typeMap.put(93, DbColumnType.TIMESTAMP);
        typeMap.put(2014, DbColumnType.TIMESTAMP);
        typeMap.put(6, DbColumnType.DOUBLE);
        typeMap.put(7, DbColumnType.DOUBLE);
        typeMap.put(8, DbColumnType.DOUBLE);
        typeMap.put(4, DbColumnType.INTEGER);
        typeMap.put(2, DbColumnType.BIG_DECIMAL);
        typeMap.put(3, DbColumnType.BIG_DECIMAL);
    }

    public static DbColumnType getColumnType(MetaTable.Column column, DbColumnType defaultType) {
        int typeCode = column.getJdbcType().TYPE_CODE;
        switch (typeCode) {
            case -7:
                return getBitType(column);
            case 2:
            case 3:
                return getNumber(column);
            case 91:
                return DbColumnType.DATE;
            case 92:
                return DbColumnType.TIME;
            case 93:
                return DbColumnType.DATE;
            default:
                return typeMap.getOrDefault(typeCode, defaultType);
        }
    }

    private static DbColumnType getBitType(MetaTable.Column column) {
        return column.getLength() > 1 ? DbColumnType.BYTE_ARRAY : DbColumnType.BOOLEAN;
    }

    private static DbColumnType getNumber(MetaTable.Column column) {
        if (column.getScale() <= 0 && column.getLength() <= 18) {
            if (column.getLength() > 9) {
                return DbColumnType.LONG;
            } else {
                return column.getLength() > 4 ? DbColumnType.INTEGER : DbColumnType.SHORT;
            }
        } else {
            return typeMap.get(column.getJdbcType().TYPE_CODE);
        }
    }


}
